package org.hiberlyzer.ui;

import java.awt.GridLayout;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JLabel;
import javax.swing.JPanel;

import org.hiberlyzer.QueryLanguage;

/**
 * Provides visual feedback about the results of a query execution.
 * @author BDotzour
 *
 */
public class StatsPanel extends JPanel
{
	private JLabel resultCountLabel;
	private JLabel queryTimeLabel;
	private JLabel queryTypeLabel;
	private Timer queryTimeTimer;
	private long currentQueryRunningTime;
	
	public StatsPanel(QueryLanguage queryType)
	{
		super(new GridLayout(1, 2));
		resultCountLabel = new JLabel("Results: 0");
		queryTimeLabel = new JLabel("Time: 00:00");
		queryTypeLabel = new JLabel(queryType.toString());
		add(resultCountLabel);
		add(queryTimeLabel);
		add(queryTypeLabel);
	}
	
	public void queryBegin()
	{
		currentQueryRunningTime = 0;
		TimerTask updateQueryTimeTask = new TimerTask(){
			public void run()
			{
				currentQueryRunningTime++;
				updateQueryTimeDisplay();
			}};
		queryTimeTimer = new Timer();
		queryTimeTimer.scheduleAtFixedRate(updateQueryTimeTask, 0, 1000);
	}
	
	public void queryEnd(long resultCount)
	{
		queryTimeTimer.cancel();
		resultCountLabel.setText("Results: " + String.valueOf(resultCount));
	}
	
	void queryTypeChanged(QueryLanguage queryType)
	{
		queryTypeLabel.setText(queryType.toString());
	}
	
	private DecimalFormat format = new DecimalFormat("#00");
	private void updateQueryTimeDisplay()
	{
		long minutes = currentQueryRunningTime / 60;
		long seconds = currentQueryRunningTime % 60;
		queryTimeLabel.setText("Time: " + format.format(minutes) + ":" + format.format(seconds));
	}
}
